﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SmartForm.Common;
using SmartForm.NetJs;
using SmartForm.Rule;
using SmartlForm.NetJs;

namespace SmartForm
{
    [ComVisible(true)]
    public partial class MainChrome : BaseForm
    {
        public ChromiumWebBrowser chromeBrowser;
        SystemRule systemRule;
        bool isStartUp = false, isConfirm = false;
        ChromeJs chromeJs;
        FormOptionJS submitFormOptionJS = null;

        /// <summary>
        /// 任务完成委托
        /// </summary>
        /// <param name="topmost"></param>
        public delegate void CompletedDelegate();
        public CompletedDelegate Completed;//定义委托实例    

        public MainChrome(SystemRule systemRule)
        {
            this.systemRule = systemRule;
            InitializeComponent();
            InitWebBrowser();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            //InitWebBrowser();
        }


        /// <summary>
        /// 浏览器初始化
        /// </summary>
        void InitWebBrowser()
        {
            if (systemRule != null)
            {
                Console.Write("InitWebBrowser");
                chromeBrowser = ChromeBrowserUtil.InitializeChromium(systemRule.LoginUrl, this.webPanel);
                chromeJs = new ChromeJs(chromeBrowser, this);
                CheckForIllegalCrossThreadCalls = false;
                chromeBrowser.RegisterJsObject("objectJS", chromeJs);
                chromeBrowser.FrameLoadEnd += Browser_FrameLoadEnd;
            }
        }

        void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            Console.Write("Browser_FrameLoadEnd");
            if (!isStartUp)
            {
                isStartUp = true;
                Thread thread = new Thread(startTask);
                thread.Start();
            }
        }

        #region ui
        public override void menu_max_Click(object sender, EventArgs e)
        {
            base.menu_max_Click(sender, e);
        }

        public override void menu_min_Click(object sender, EventArgs e)
        {
            base.menu_min_Click(sender, e);
        }

        public override void menu_close_Click(object sender, EventArgs e)
        {
            exit();
        }
        public override void menu_MouseHover(object sender, EventArgs e)
        {
            base.menu_MouseHover(sender, e);
        }

        public override void menu_MouseLeave(object sender, EventArgs e)
        {
            base.menu_MouseLeave(sender, e);
        }

        public override void menu_MouseMove(object sender, MouseEventArgs e)
        {
            base.menu_MouseMove(sender, e);
        }

        public override void drag_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks > 1)
            {
                base.menu_max_Click(sender, e);
            }
            else
            {
                base.drag_MouseDown(sender, e);
            }
        }

        public void exit()
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要退出吗?", "退出系统", messButton);
            if (dr == DialogResult.OK)
            {
                close();
            }
        }

        #endregion

        private void submitBtn_Click(object sender, EventArgs e)
        {
            if (submitFormOptionJS != null)
            {
                if (submitFormOptionJS.JS.Contains("return "))
                {
                    chromeJs.ExeScript(submitFormOptionJS.GetJS());
                }
                else
                {
                    chromeJs.ExeScriptResult(submitFormOptionJS.GetJS());
                }
                isConfirm = true;
                string btnTip = "您已确认提交！";
                MessageBox.Show(btnTip);

                labelTip.Text = btnTip;
                submitBtn.Enabled = false;
                submitBtn.Text = "已确认提交";
                submitBtn.BackColor = Color.DarkGray;
                submitBtn.ForeColor = Color.White;

                if (submitFormOptionJS.Completed)
                {
                    //结束本次任务 - 右下角提示完成信息 
                    Completed.Invoke();
                    this.Dispose();
                }
            }
            else
            {
                MessageBox.Show("当前无任何需要确认的内容！");
            }
        }

        public void startTask()
        {
            Delay.DelaySecond(3);
            string js = string.Empty;
            //登录账户密码
            if (systemRule.LoginJS != null && systemRule.LoginJS.Count > 0)
            {
                foreach (var item in systemRule.LoginJS)
                {
                    js = item.JS.Replace("$account", systemRule.Account).Replace("$password", systemRule.Password);
                    LogUtil.WriteLog(js);
                    if (item.JS.Contains("return "))
                    {
                        chromeJs.ExeScript(js);
                    }
                    else
                    {
                        chromeJs.ExeScriptResult(js);
                    }
                    if (item.Second > 0)
                    {
                        Delay.DelaySecond(item.Second);
                    }
                }
            }
            //填写表单
            foreach (var item in systemRule.FormOptionJSList)
            {
                if (!string.IsNullOrEmpty(item.JS))
                {
                    js = item.GetJS();
                    LogUtil.WriteLog(js);
                    if (item.Submit)
                    {
                        submitFormOptionJS = item;
                        isConfirm = false;//重置未确认操作
                        //提示用户确认表单提交
                        labelTip.Text = "表单已经帮您填好了，请确认无误后点击以下“确认提交”按钮提交。";
                        submitBtn.Enabled = true;
                        submitBtn.Text = "确认提交";
                        submitBtn.BackColor = Color.MediumSeaGreen;
                        MessageBox.Show("表单已填写完成，请您检测后确认提交！");

                        //如果非完成项，需等待用户执行完毕后重新加载
                        if (!item.Completed)
                        {
                            SubmitConfirmWait();
                        }
                    }
                    else
                    {
                        if (item.JS.Contains("return "))
                        {
                            chromeJs.ExeScript(js);
                        }
                        else
                        {
                            chromeJs.ExeScriptResult(js);
                        }
                        if (item.Second > 0)
                        {
                            Delay.DelaySecond(item.Second);
                        }
                    }
                }
                //是否为完成标记，如果为手动确认，需要在确认处进行处理完成事件
                if (item.Completed && !item.Submit)
                {
                    //结束本次任务 - 右下角提示完成信息 
                    Completed.Invoke();
                    this.Dispose();
                }
            }
        }

        /// <summary>
        /// 等待确认提交
        /// </summary>
        public void SubmitConfirmWait()
        {
            if (!isConfirm)
            {
                //等待确认提交
                Delay.DelaySecond(1);
                SubmitConfirmWait();
            }
        }
    }
}
